package system

import (
	"bottle/global"
	"bottle/model/common/response"
	"bottle/model/system"
	systemReq "bottle/model/system/request"
	systemRes "bottle/model/system/response"
	"bottle/utils"
	"encoding/json"
	"fmt"
	"github.com/gin-gonic/gin"
	"time"
)

type MessageApi struct{}

func (m *MessageApi) GetConversations(c *gin.Context) {
	var req systemReq.GetMessageListReq
	err := c.ShouldBind(&req)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	err = utils.Verify(req, utils.UUIDVerify)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	type messageEg struct {
		OtherUserId string    `json:"other_user_id"`
		MessageId   string    `json:"message_id"`
		Payload     string    `json:"payload"`
		Timestamp   time.Time `json:"timestamp"`
		SenderId    string    `json:"senderId"`
		ReceiverId  string    `json:"receiverId"`
	}
	var messageList []messageEg
	subQuery1 := global.GVA_DB.Model(&system.Message{}).Order("id DESC").Limit(99999)
	selectStr := fmt.Sprintf("CASE WHEN sender_id='%s' THEN receiver_id ELSE sender_id END AS other_user_id,message_id,payload,timestamp,sender_id,receiver_id", req.UUID)
	global.GVA_DB.Table("(?) as u", subQuery1).Select(selectStr).Where("sender_id = ?", req.UUID).Or("receiver_id = ?", req.UUID).Group("other_user_id").Find(&messageList)

	//封装数据格式为GoEasy的会话列表conversations格式
	var userUUID []string
	for k, v := range messageList {
		err = json.Unmarshal([]byte(v.Payload), &messageList[k].Payload)
		userUUID = append(userUUID, v.OtherUserId)
	}
	var userData []struct {
		Username string
		Avatar   string
		UUID     string
	}
	global.GVA_DB.Model(&system.User{}).Where("uuid in ?", userUUID).Select("username", "avatar", "uuid").Scan(&userData)

	userMap := make(map[string]systemRes.UserData)
	for _, v := range userData {
		userMap[v.UUID] = systemRes.UserData{Avatar: v.Avatar, Nickname: v.Username}
	}

	var conversionList []systemRes.Conversations
	for _, v := range messageList {
		var lastMessage systemRes.LastMessage
		err = json.Unmarshal([]byte(v.Payload), &lastMessage.Payload)
		lastMessage.Type = "text"
		lastMessage.Timestamp = v.Timestamp.UnixMilli()
		lastMessage.SenderId = v.SenderId
		lastMessage.ReceiverId = v.ReceiverId
		cv := systemRes.Conversations{
			UserId:      v.OtherUserId,
			Data:        userMap[v.OtherUserId],
			LastMessage: lastMessage,
		}
		conversionList = append(conversionList, cv)
	}
	response.OkWithData(conversionList, c)
}

func (m *MessageApi) IsNeedAIMessage(c *gin.Context)  {
	var req systemReq.UUIDReq
	err := c.ShouldBind(&req)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	err = utils.Verify(req, utils.UUIDVerify)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}

	var user system.User
	err = global.GVA_DB.Where("uuid = ?", req.UUID).First(&user).Error
	if err != nil {
		response.Fail(c)
		return
	}
	var message system.Message
	var res systemRes.AiMessageRes
	if user.Gender == 1 {
		err = global.GVA_DB.Where("sender_id = ?", "d7226d01-fa84-4806-ab58-ae279bd3b367").Where("receiver_id = ?", user.UUID).First(&message).Error
		global.GVA_DB.Model(&system.User{}).Where("id = 5").First(&res)
	}else if user.Gender == 2 {
		err = global.GVA_DB.Where("sender_id = ?", "869dc0b7-660a-4747-a033-462afebb6ce7").Where("receiver_id = ?", user.UUID).First(&message).Error
		global.GVA_DB.Model(&system.User{}).Where("id = 4").First(&res)
	}else {
		response.Fail(c)
		return
	}

	//如果没发过消息则返回ai发送消息需要用到得数据
	if err != nil {
		response.OkWithData(res, c)
		return
	}
	response.FailWithMessage("ai已经发送过一次消息", c)
	return
}